# -*- coding:utf-8 -*-
import eventlet
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import exists
eventlet.monkey_patch()
from eventlet import wsgi
from flask import Flask, request
from flask_cors import CORS
import json

from dealRequest import *
from gl import *
from models import *

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///user.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
DEBUG = True
db = SQLAlchemy(app)
CORS(app, supports_credentials=True)


# #定义ORM 数据库关系映射
class User(db.Model):
    __tablename__ = 'data'
    id = db.Column(db.Integer, primary_key=True)
    role = db.Column(db.Integer) # 0 卫星 | 1 用户
    userId = db.Column(db.String(255), unique=True)
    userKey = db.Column(db.String(255), unique=True)
    preRandom = db.Column(db.String(255), unique=False)
    # random18：计算 userId 用，让用户idcard和 userId 一一对应，避免重复注册。
    IDcard= db.Column(db.String(255), unique=True)
    def __init__(self, role, userId, userKey, preRandom,IDcard):
        self.role = role
        self.userId = userId
        self.userKey = userKey
        self.preRandom = preRandom
        self.IDcard=IDcard
    def __repr__(self):
        return '<Uid %r>' % self.userId

# 初始化数据库是才开启
# 创建表格、初始化数据库、插入数据
####################################
db.drop_all()
db.create_all()
db.init_app(app)
satallite=User(
    '0',
    '06fa43a4b4a63b622e36e3cd4ef55fcfec070b97', 
    '580ade0f132b4228ea4fe1a289f318f2402fdcd2682ed057a3785fed4312f9f3',
    '55868018469076085065818153351715',
    '0'
    )
db.session.add(satallite)
db.session.commit()
################################

@app.route('/')
def index():
    return 'NCC is started!'


@app.route('/reqUserInfo', methods=['GET', 'POST'])
def reqUserInfo():
    if(request.data):
        try:
            data = json.loads(request.data)
            retUserInfo = getUserInfo(data)
            if retUserInfo == "0":
                return "someting error...", 500
            return json.dumps(retUserInfo)
        except Exception, e:
            print e
            return "someting error...", 500
            
    return 'tbc', 500

# 接收卫星发来的satalliteData, userData
@app.route('/identityCheck', methods=['GET', 'POST'])
def identityCheck():
    # 取post信息做验证
    if(request.data):
        # clear_and_add(request.data)
        data = json.loads(request.data)
        try:
            userData = data['userData']
            satalliteData = data['satalliteData']
        except Exception, e:
            print e
            return json.dumps({
                'Code':"1"
            }), 500

        # 处理认证选项
        try:
            new_options = userData['Options']
        except Exception, e:
            pass

        # 认证用户和卫星
        try:
            masterKey = authCheck(userData, satalliteData)
            if masterKey == '0':
                return json.dumps({
                    'Code':"1",
                    'status':"MAC error"
                }), 500
            # test
            retData = retSatallite(masterKey)
            return json.dumps(retData)
        except Exception, e:
            print e
            return json.dumps({
                'Code':"1",
                'status':"auth error"
            }), 500
    else:
        return 'invalide method', 500

# 用户注册
@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.data:
        IDcard = json.loads(request.data)["Idcard"]
        # 查询是否离线已经注册
        if (db.session.query(exists().where(User.IDcard== IDcard)).scalar()):
            return getAuthID(IDcard)
        # 离线注册，生成user注册信息
        random18 = str(random.randint(100000000000000000, 999999999999999999))
        userId = hashlib.sha1(IDcard + random18).hexdigest()
        preRandom = str(random.randint(10000000000000000000000000000000, 99999999999999999999999999999999))
        userKey = hashlib.sha1(IDcard + preRandom).hexdigest()
        # 存入数据库
        try:
            new_user = User('1', userId, userKey, preRandom,IDcard)
            db.session.add(new_user)
            db.session.commit()
        except:
            return 'database error', 500
        # 返回给用户
        return json.dumps({
            "userId": userId,
            "userKey": userKey,
            "preRandom": preRandom,
             "status":'0'
        })
    return 'method error', 500


if __name__ == "__main__":
   
    # wsgi.server(eventlet.listen(('127.0.0.1', 7543)), app,debug=True)
    app.run(
            host='127.0.0.1',
            port=7543,#端口
            debug=True
            )

        